from contextlib import asynccontextmanager

from fastapi import FastAPI

from example.globals import app_config
from example.globals.log import global_logger
from example.globals.nacos import nacos_client
from example.util.ip_util import get_real_ip


@asynccontextmanager
async def lifespan(app: FastAPI):
    _on_start()
    yield
    _on_shutdown()


# 服务信息
service_name = app_config.project.name
service_ip = app_config.server.ip if app_config.server.ip else get_real_ip()
service_port = app_config.server.port


# 容器启动
def _on_start():
    global_logger.info("app start ...")
    if app_config.nacos.enable:
        global_logger.info("register to nacos")
        nacos_client.register(service_name, service_ip, service_port)


# 容器关闭
def _on_shutdown():
    global_logger.info("app shutdown ...")
    if app_config.nacos.enable:
        global_logger.info("deregister from nacos")
        nacos_client.deregister(service_name, service_ip, service_port)
